import numpy as np
import json
from sklearn import model_selection as mo
from sklearn import svm
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV
# 自添
import matplotlib
matplotlib.use('TkAgg')
# 自添结束
import matplotlib.pyplot as plt
import skimage

file1 = "./train_release-fasd-ycbcr-real.json"
file2 = "./train_release-fasd-ycbcr-hsv-attack.json"
file3 = "./test_release-fasd-ycbcr-real.json"
file4 = "./test_release-fasd-ycbcr-hsv-attack.json"


# file = "./video.json"



x_train = []
x_test = []
y_train = []
y_test = []



with open(file1, 'r')as f:
    list = json.load(f)
    data1 = np.array(list)

with open(file2, 'r')as f:
    list = json.load(f)
    data2 = np.array(list)

with open(file3, 'r')as f:
    list = json.load(f)
    data3 = np.array(list)

with open(file4, 'r')as f:
    list = json.load(f)
    data4 = np.array(list)

# 训练集
for i in range(len(data1)):
    x_train.append(np.array([data1[i]]))
    y_train.append(0)
    
for i in range(len(data2)):
    x_train.append(np.array([data2[i]]))
    y_train.append(1)

# 测试集
for i in range(len(data3)):
    x_test.append(np.array([data3[i]]))
    y_test.append(0)
    
for i in range(len(data4)):
    x_test.append(np.array([data4[i]]))
    y_test.append(1)

x_train = np.array((x_train))
x_test = np.array((x_test))
y_train = np.array((y_train))
y_test = np.array((y_test))

# classifier = svm.SVC(C=1, kernel='rbf', gamma=30, decision_function_shape='ovo')  # C=0.8, gamma=20
svc = svm.SVC()
# model = svm.SVC(C=1, kernel='rbf', gamma=30, decision_function_shape='ovo')
# classifier = svm.SVC(C=0.8, kernel='linear', decision_function_shape='ovr')
# classifier = svm.SVC(C=0.8, decision_function_shape='ovr')
parameters={'kernel':['linear','rbf','sigmoid','poly'],'C':np.linspace(0.1,20,50),'gamma':np.linspace(0.1,20,20)}
model = GridSearchCV(svc,parameters,cv=5,scoring='accuracy')
model.fit(x_train,y_train)
model.best_params_

# classifier.fit(x_train, y_train)
# 训练集的准确率
print("SVM-输出训练集的准确率为：",model.score(x_train,y_train))
y_hat = model.predict(x_train)
# show_accuracy(y_hat,y_train,'训练集')
# print('x_train——y_hat',y_hat)
print(classification_report(y_train, y_hat, digits=4))
y_hat = model.predict(x_test)
# show_accuracy(y_hat,y_test,'训练集')
print("SVM-输出测试集的准确率为：",model.score(x_test,y_test))
# print('x_test——y_hat',y_hat)
print(classification_report(y_test, y_hat, digits=4))

plt.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1],
            s=80, facecolors='none')
plt.scatter(x_train[:, 0], x_train[:, 1], c=Y, cmap=plt.cm.Paired)
 
plt.axis('tight')


